package a;

import java.io.File;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import a.SwingShell.AdvancedVerifier;
import a.SwingShell.InteractiveLogic;
import a.SwingShell.TerminalDialog;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.InteractiveCallback;
import ch.ethz.ssh2.KnownHosts;
import ch.ethz.ssh2.Session;

public class ConnectionThread_ extends Thread
{
	class InteractiveLogic implements InteractiveCallback
	{
		int promptCount = 0;
		String lastError;
		public InteractiveLogic(String lastError)
		{
			this.lastError = lastError;
		}
		public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt,
				boolean[] echo) throws IOException
		{
			String[] result = new String[numPrompts];

			for (int i = 0; i < numPrompts; i++)
			{
				String[] content = new String[] { lastError, name, instruction, prompt[i] };
				if (lastError != null)
				{
					lastError = null;
				}
/*				EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "Keyboard Interactive Authentication",
						content, !echo[i]);
				esd.setVisible(true);
				if (esd.answer == null)
					throw new IOException("Login aborted by user");
*/
				result[i] ="log";// esd.answer;
				promptCount++;
			}

			return result;
		}
		public int getPromptCount()
		{
			return promptCount;
		}
	}
	KnownHosts database;
	String hostname;
	String username,a_,b_;
	JPanel loginPanel;
	JFrame loginFrame;
	public ConnectionThread_(String hostname, String username,KnownHosts database_,String a,String b,JPanel loginPanel_,JFrame loginFrame_ )
	{
		this.hostname = hostname;
		this.username = username;
		database=database_;a_=a;b_=b;loginPanel=loginPanel_;loginFrame=loginFrame_;
	}
	public void run()
	{
		Connection conn = new Connection(hostname);
		try
		{
			String[] hostkeyAlgos = database.getPreferredServerHostkeyAlgorithmOrder(hostname);
			if (hostkeyAlgos != null)
				conn.setServerHostKeyAlgorithms(hostkeyAlgos);
			conn.connect(new Adva());
			boolean enableKeyboardInteractive = true;
			boolean enableDSA = true;
			boolean enableRSA = true;
			String lastError = null;
			while (true)
			{
				if ((enableDSA || enableRSA) && conn.isAuthMethodAvailable(username, "publickey"))
				{
					if (enableDSA)
					{
						File key = new File(a_);

						/*if (key.exists())
						{
							EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "DSA Authentication",
									new String[] { lastError, "Enter DSA private key password:" }, true);
							esd.setVisible(true);
							
							boolean res =conn.authenticateWithPublicKey(username, key, "log");
							if (res == true)
								break;
							lastError = "DSA authentication failed.";
						}*/
						enableDSA = false; // do not try again
					}
					if (enableRSA)
					{
						File key = new File(b_);
						/*if (key.exists())
						{
							EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "RSA Authentication",
									new String[] { lastError, "Enter RSA private key password:" }, true);
							esd.setVisible(true);
							//boolean res = conn.authenticateWithPublicKey(username, key, esd.answer);
							boolean res = conn.authenticateWithPublicKey(username, key, "log");
							if (res == true)
								break;
							lastError = "RSA authentication failed.";
						}*/
						enableRSA = false; // do not try again
					}
					continue;
				}
				if (enableKeyboardInteractive && conn.isAuthMethodAvailable(username, "keyboard-interactive"))
				{
					InteractiveLogic il = new InteractiveLogic(lastError);
					boolean res = conn.authenticateWithKeyboardInteractive(username, il);

					if (res == true)
						break;

					if (il.getPromptCount() == 0)
					{
						lastError = "Keyboard-interactive does not work.";
						enableKeyboardInteractive = false; // do not try this again
					}
					else
					{
						lastError = "Keyboard-interactive auth failed."; // try again, if possible
					}
					continue;
				}
				if (conn.isAuthMethodAvailable(username, "password"))
				{
					/*final EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame,
							"Password Authentication",
							new String[] { lastError, "Enter password for " + username }, true);
					esd.setVisible(true);
					if (esd.answer == null)
						throw new IOException("Login aborted by user");
					boolean res = conn.authenticateWithPassword(username, "log");
					if (res == true)
						break;
					lastError = "Password authentication failed."; // try again, if possible
					continue;*/
				}
				throw new IOException("No supported authentication methods available.");
			}
			Session sess = conn.openSession();
			int x_width = 90;
			int y_width = 30;
			sess.requestPTY("dumb", x_width, y_width, 0, 0, null);
			sess.startShell();
			//TerminalDialog td = new TerminalDialog(_frame, username + "@" + hostname, sess, x_width, y_width);
			TerminalDialog_ td = new TerminalDialog_(username + "@" + hostname, sess, x_width, y_width);
			td.setSize(100, 100);
			loginPanel.add(td);
			/*TerminalDialog td1 = new TerminalDialog(username + "@" + hostname, sess, x_width, y_width);
			td1.setSize(100, 100);
			loginPanel.add(td1);*/
//			/td.setVisible(true);
		}
		catch (IOException e)
		{
			//e.printStackTrace();
			System.out.println("Exception: " + e.getMessage());
			//JOptionPane.showMessageDialog(loginFrame, "Exception: " + e.getMessage());
		}
		/*conn.close();
		Runnable r = new Runnable()
		{
			public void run()
			{
				loginFrame.dispose();
			}
		};

		SwingUtilities.invokeLater(r);*/
	}
}